package br.com.centrodata.controller;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.Validations;
import br.com.centrodata.dao.UserDao;
import br.com.centrodata.model.User;
import org.hibernate.HibernateException;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;

/**
 *
 * @author João Fernandes Lima Neto
 */
@Resource
public class UserController implements GenericController<User> {

    private final Result    result;
    private final Validator validator;
    private       UserDao   dao;

    public UserController(UserDao dao, Result result, Validator validator) {
        this.dao       = dao;
        this.result    = result;
        this.validator = validator;
    }

    @Path("user/index")
    @Get
    @Override
    public void index() {
        result.include("users", dao.search());
    }

    @Path("/user/new")
    @Get
    @Override
    public void form() {
    }

    @Path("/user/{user.id}")
    @Get
    @Override
    public void form(User user) {
        result.include("user", dao.search(user.getId()));
    }

    @Path("/user/delete/{user.id}")
    @Get
    @Override
    public void delete(User user) {
        try{
            
            user = dao.search(user.getId());
            
            dao.del(user);
            result.include("notice", "Usuario [" + user.getNome() + "] deletado com sucesso!");
            result.redirectTo(this).index();
        }catch(HibernateException hb){
            result.include("error", "Ocorreu um erro ao tentar deletar o Usuário!");
            result.redirectTo(this).index();
        }
    }

    @Path("/user/save")
    @Post
    @Override
    public void save(final User user) {

        boolean isEdit = user.getId() > 0;
        
        
        /* se estiver Editando */
        if(isEdit){
            validator.checking(new Validations() {
                {
                    that(user, is(notNullValue()),                   "user", "invalid_object");
                    that(!(user.getSenha().length() < 6),            "user", "invalid_password"  );
                }
            });

            validator.onErrorUsePageOf(this).form();
            
            this.dao.update(user);
            
            result.include("notice", "Usuário [" + user.getNome() + "] atualizado com sucesso.");
        }else{
            /* Se estiver inserindo */
            validator.checking(new Validations() {
                {
                    that(user, is(notNullValue()),                   "user", "invalid_object");
                    that(!dao.existisUserWithLogin(user.getLogin()), "user", "login_already_exists" );
                    that(!(user.getSenha().length() < 6),            "user", "invalid_password"  );
                }
            });
            
            validator.onErrorUsePageOf(this).form();
            
            this.dao.add(user);
            
            result.include("notice", "Usuário [" + user.getNome() + "] inserido com sucesso.");
        }
        result.forwardTo(this).index();
    }
    
}
